package cn.innosmart.aq.view.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.fourmob.datetimepicker.date.DatePickerDialog;
import com.sleepbot.datetimepicker.time.RadialPickerLayout;
import com.sleepbot.datetimepicker.time.TimePickerDialog;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import cn.innosmart.aq.R;
import cn.innosmart.aq.bean.Reminder;
import cn.innosmart.aq.customize.datetimepicker.WeekChooseView;
import cn.innosmart.aq.customize.switchbutton.CheckSwitchButton;
import cn.innosmart.aq.reminder.ReminderManager;
import cn.innosmart.aq.util.SharedUtil;
import cn.innosmart.aq.view.activity.base.BaseActivity;

/**
 * Created by David on 2016/1/25.
 */
public class ReminderActivity extends BaseActivity implements TimePickerDialog.OnTimeSetListener, DatePickerDialog.OnDateSetListener {
    public static final String DATEPICKER_TAG = "datepicker";
    public static final String TIMEPICKER_TAG = "timepicker";
    private final int MODIFY = 1;
    private Toolbar toolbar;
    private LinearLayout llDate;
    private LinearLayout llTime;
    private LinearLayout llRepeat;
    private TextView tvDate;
    private TextView tvTime;
    private TextView tvRepeat;
    private EditText etReminderTitle;
    private EditText etReminderContent;
    private Calendar calendar;
    private TimePickerDialog timePickerDialog;
    private DatePickerDialog datePickerDialog;
    private CheckBox cbEnable;
    private Spinner spRepeatType;
    private Spinner spRepeatPeriodic;
    private CheckSwitchButton repeatSwitch;
    private LinearLayout llSetRepeat;
    private WeekChooseView weekChoose;
    private Reminder reminder;
    private int flag = 0;
    private Toolbar.OnMenuItemClickListener onMenuItemClick = new Toolbar.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem menuItem) {
            switch (menuItem.getItemId()) {
                case R.id.action_save:
                    saveReminder();
                    break;
            }
            return true;
        }
    };
    private Menu menus;
    private View.OnClickListener onClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.ll_date:
                    setDate();
                    break;
                case R.id.ll_time:
                    setTime();
                    break;
            }
        }
    };
    private View.OnClickListener onNavigationClickListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            exit();
        }
    };

    public void setDate() {
        datePickerDialog.setVibrate(true);
        datePickerDialog.setYearRange(1985, 2028);
        datePickerDialog.setCloseOnSingleTapDay(false);
        if (!datePickerDialog.isAdded()) {
            datePickerDialog.show(getSupportFragmentManager(), DATEPICKER_TAG);
        }

    }

    public void setTime() {
        timePickerDialog.setVibrate(true);
        timePickerDialog.setCloseOnSingleTapMinute(false);
        if (!timePickerDialog.isAdded()) {
            timePickerDialog.show(getSupportFragmentManager(), TIMEPICKER_TAG);
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_reminder, menu);
        menus = menu;
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reminder);
        setBar();
        Intent intent = getIntent();
        if (intent != null)
            flag = intent.getIntExtra("flag", -1);
        if (flag == 1) {
            reminder = intent.getParcelableExtra("reminder");
        } else {
            reminder = new Reminder();
        }
        if (reminder.repeatDatas == null) {
            reminder.repeatDatas = new HashMap<>();
        }
        setBar();
        assignViews();
        initialViewsByData();
        assignListeners();
    }

    private void setBar() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("");
        if (flag == 1) {
//            toolbar.setTitle(getString(R.string.toolbar_modify_reminder));
            ((TextView) findViewById(R.id.tv_toolbar)).setText(getString(R.string.toolbar_modify_reminder));
        } else {
//            toolbar.setTitle(getString(R.string.toolbar_add_reminder));
            ((TextView) findViewById(R.id.tv_toolbar)).setText(getString(R.string.toolbar_add_reminder));
        }
        ((ImageView) findViewById(R.id.iv_headicon)).setImageResource(R.drawable.toolbar_back);
        setSupportActionBar(toolbar);
//        toolbar.setNavigationOnClickListener(onNavigationClickListener);
        findViewById(R.id.iv_headicon).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                exit();
            }
        });
        toolbar.setOnMenuItemClickListener(onMenuItemClick);
    }


    private void saveReminder() {
        String title = etReminderTitle.getText().toString().trim();
        String content = etReminderContent.getText().toString().trim();
        String date = tvDate.getText().toString().trim();
        String time = tvTime.getText().toString().trim();
        if (TextUtils.isEmpty(title)) {
            showToast(getString(R.string.reminder_title_no_empty));
            return;
        }
        if (TextUtils.isEmpty(content)) {
            showToast(getString(R.string.reminder_content_no_empty));
            return;
        }
        if (TextUtils.isEmpty(date)) {
            showToast(getString(R.string.reminder_date_no_empty));
            return;
        }
        if (TextUtils.isEmpty(time)) {
            showToast(getString(R.string.reminder_time_no_empty));
            return;
        }
//      if (TextUtils.isEmpty(repeat)) {
//            showToast("备忘提醒的重复设置不能为空!");
//            return;
//      }
        reminder.title = title;
        reminder.date = date;
        reminder.time = time;
        reminder.content = content;
        if (cbEnable.isChecked()) {
            //SetAlarm
            reminder.isEnable = true;
            if (flag == MODIFY) {
                SharedUtil.getInstance().updateReminder(reminder);
            } else {
                SharedUtil.getInstance().addReminder(reminder);
            }
            ReminderManager.createAlarm(ReminderActivity.this, reminder);
        } else {
            reminder.isEnable = false;
            if (flag == MODIFY) {
                SharedUtil.getInstance().updateReminder(reminder);
            } else {
                SharedUtil.getInstance().addReminder(reminder);
            }
        }
        setResult(flag);
        finish();
    }

    private void assignViews() {
        weekChoose = (WeekChooseView) findViewById(R.id.week_choose);
        llSetRepeat = (LinearLayout) findViewById(R.id.ll_set_repeat);
        repeatSwitch = (CheckSwitchButton) findViewById(R.id.repeat_switch);
        spRepeatType = (Spinner) findViewById(R.id.sp_repeat_type);
        spRepeatPeriodic = (Spinner) findViewById(R.id.sp_repeat_periodic);
        calendar = Calendar.getInstance();
        cbEnable = (CheckBox) findViewById(R.id.cb_enable);
        llDate = (LinearLayout) findViewById(R.id.ll_date);
        llTime = (LinearLayout) findViewById(R.id.ll_time);
        llRepeat = (LinearLayout) findViewById(R.id.ll_repeat);
        tvDate = (TextView) findViewById(R.id.tv_date);
        tvTime = (TextView) findViewById(R.id.tv_time);
        tvRepeat = (TextView) findViewById(R.id.tv_repeat);
        etReminderTitle = (EditText) findViewById(R.id.et_reminder_title);
        etReminderContent = (EditText) findViewById(R.id.et_reminder_content);
    }

    private void initialViewsByData() {
        if (flag == MODIFY) {
            cbEnable.setChecked(reminder.isEnable);
        } else {
            cbEnable.setChecked(true);
        }
        if (flag == MODIFY) {
            if (reminder.year != 0)
                calendar.set(Calendar.YEAR, reminder.year);
            calendar.set(Calendar.MONTH, reminder.month);
            calendar.set(Calendar.DAY_OF_MONTH, reminder.day);
            calendar.set(Calendar.HOUR_OF_DAY, reminder.hour);
            calendar.set(Calendar.MINUTE, reminder.minitue);
            calendar.set(Calendar.SECOND, 0);
            calendar.set(Calendar.MILLISECOND, 0);
        }
        timePickerDialog = TimePickerDialog.newInstance(this, calendar.get(Calendar.HOUR_OF_DAY), calendar.get(Calendar.MINUTE), true, false);
        datePickerDialog = DatePickerDialog.newInstance(this, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH), true);
        etReminderTitle.setText(reminder.title);
        etReminderContent.setText(reminder.content);
        tvDate.setText(reminder.date);
        tvTime.setText(reminder.time);
        if (flag != MODIFY) {
            repeatSwitch.setChecked(false);
            spRepeatType.setSelection(1);
            weekChoose.setChecked(calendar.get(Calendar.DAY_OF_WEEK) - 1, true);
            reminder.repeatDatas.put(calendar.get(Calendar.DAY_OF_WEEK) - 1, Long.valueOf((spRepeatPeriodic.getSelectedItemPosition() + 1) * 7 * 24 * 60 * 60 * 1000));
        } else if (flag == MODIFY) {
            switch (reminder.repeat) {
                case Reminder.NERVER:
                    repeatSwitch.setChecked(false);
                    break;
                case Reminder.EVERYPERIODICDAY:
                    repeatSwitch.setChecked(true);
                    llSetRepeat.setVisibility(View.VISIBLE);
                    spRepeatType.setSelection(0);
//                    weekChoose.setVisibility(View.GONE);
                    spRepeatPeriodic.setSelection(reminder.repeatperiodic - 1);
                    tvRepeat.setText(String.format(getString(R.string.periodic_every_day), reminder.repeatperiodic));

                    break;
                case Reminder.EVERYOERIODICWEEK:
                    repeatSwitch.setChecked(true);
                    llSetRepeat.setVisibility(View.VISIBLE);
                    spRepeatType.setSelection(1);
//                    weekChoose.setVisibility(View.VISIBLE);
                    spRepeatPeriodic.setSelection(reminder.repeatperiodic - 1);
                    tvRepeat.setText(selectCurrentWeek());
                    if (reminder.repeatDatas == null) {
                        reminder.repeatDatas = new HashMap<>();
                    }
                    if (reminder.repeatDatas.containsKey(1)) {
                        weekChoose.setChecked(1, true);
                    }
                    if (reminder.repeatDatas.containsKey(2)) {
                        weekChoose.setChecked(2, true);
                    }
                    if (reminder.repeatDatas.containsKey(3)) {
                        weekChoose.setChecked(3, true);
                    }
                    if (reminder.repeatDatas.containsKey(4)) {
                        weekChoose.setChecked(4, true);
                    }
                    if (reminder.repeatDatas.containsKey(5)) {
                        weekChoose.setChecked(5, true);
                    }
                    if (reminder.repeatDatas.containsKey(6)) {
                        weekChoose.setChecked(6, true);
                    }
                    if (reminder.repeatDatas.containsKey(0)) {
                        weekChoose.setChecked(0, true);
                    }
                    break;
            }
        }
    }

    private void assignListeners() {
        llDate.setOnClickListener(onClickListener);
        llTime.setOnClickListener(onClickListener);
        llRepeat.setOnClickListener(onClickListener);
        spRepeatType.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (position == 0) {
                    weekChoose.setVisibility(View.GONE);
                    if (reminder.repeatDatas == null)
                        reminder.repeatDatas = new HashMap<Integer, Long>();
                    reminder.repeat = Reminder.EVERYPERIODICDAY;
                    reminder.repeatDatas.put(7, Long.valueOf((spRepeatPeriodic.getSelectedItemPosition() + 1) * 24 * 60 * 60 * 1000));
                    tvRepeat.setText(String.format(getString(R.string.periodic_every_day), spRepeatPeriodic.getSelectedItemPosition() + 1));
                } else {
                    if (reminder.repeatDatas == null)
                        reminder.repeatDatas = new HashMap<Integer, Long>();
                    if (reminder.repeatDatas.containsKey(7))
                        reminder.repeatDatas.remove(7);
                    reminder.repeat = Reminder.EVERYOERIODICWEEK;
                    Iterator iterator = reminder.repeatDatas.entrySet().iterator();
                    while (iterator.hasNext()) {
                        Map.Entry entry = (Map.Entry) iterator.next();
                        entry.setValue(Long.valueOf((spRepeatPeriodic.getSelectedItemPosition() + 1) * 7 * 24 * 60 * 60 * 1000));
                        int key = (int) entry.getKey();
                        weekChoose.setChecked(key, true);
                    }
                    tvRepeat.setText(selectCurrentWeek());
                    weekChoose.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        spRepeatPeriodic.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                int periodic = position + 1;
                reminder.repeatperiodic = periodic;
                if (reminder.repeatDatas == null)
                    reminder.repeatDatas = new HashMap<Integer, Long>();
                if (reminder.repeat == Reminder.EVERYPERIODICDAY) {
                    Iterator iterator = reminder.repeatDatas.entrySet().iterator();
                    while (iterator.hasNext()) {
                        Map.Entry entry = (Map.Entry) iterator.next();
                        entry.setValue(Long.valueOf(periodic * 24 * 60 * 60 * 1000));
                    }
                } else if (reminder.repeat == Reminder.EVERYOERIODICWEEK) {
                    Iterator iterator = reminder.repeatDatas.entrySet().iterator();
                    while (iterator.hasNext()) {
                        Map.Entry entry = (Map.Entry) iterator.next();
                        entry.setValue(Long.valueOf(periodic * 7 * 24 * 60 * 60 * 1000));
                    }
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });
        repeatSwitch.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    llSetRepeat.setVisibility(View.VISIBLE);
                    if (reminder.repeatDatas.containsKey(7)) {
                        //显示每天的界面
                        tvRepeat.setText(String.format(getString(R.string.periodic_every_day), spRepeatPeriodic.getSelectedItemPosition() + 1));
                    } else {
                        //显示每周的界面
                        tvRepeat.setText(selectCurrentWeek());
                    }

                } else {
                    //清空数据
                    llSetRepeat.setVisibility(View.GONE);
                    tvRepeat.setText(R.string.repeat_never);
                    reminder.repeat = Reminder.NERVER;

                }
            }
        });
        weekChoose.setOnRepeatStatusChanged(new WeekChooseView.OnRepeatStatusChanged() {
            @Override
            public void onCheckChanged(int position, boolean isChecked) {
                int periodic = spRepeatPeriodic.getSelectedItemPosition() + 1;
                if (reminder.repeatDatas == null) {
                    reminder.repeatDatas = new HashMap<Integer, Long>();
                }
                if (isChecked)
                    reminder.repeatDatas.put(position, Long.valueOf(periodic * 7 * 24 * 60 * 60 * 1000));
                else {
                    if (reminder.repeatDatas.containsKey(position)) {
                        reminder.repeatDatas.remove(position);
                    }
                }
                tvRepeat.setText(selectCurrentWeek());
            }
        });
    }

    private String selectCurrentWeek() {
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append(getString(R.string.every_periodic));
        if (reminder.repeatDatas == null) {
            reminder.repeatDatas = new HashMap<>();
        }
        if (reminder.repeatDatas.containsKey(1)) {
            stringBuilder.append(getString(R.string.reminder_monday));
        }
        if (reminder.repeatDatas.containsKey(2)) {
            stringBuilder.append(getString(R.string.reminder_tuesday));
        }
        if (reminder.repeatDatas.containsKey(3)) {
            stringBuilder.append(getString(R.string.reminder_wensday));
        }
        if (reminder.repeatDatas.containsKey(4)) {
            stringBuilder.append(getString(R.string.reminder_thursday));
        }
        if (reminder.repeatDatas.containsKey(5)) {
            stringBuilder.append(getString(R.string.reminder_friday));
        }
        if (reminder.repeatDatas.containsKey(6)) {
            stringBuilder.append(getString(R.string.reminder_saturday));
        }
        if (reminder.repeatDatas.containsKey(0)) {
            stringBuilder.append(getString(R.string.reminder_sunday));
        }
        if (stringBuilder.charAt(stringBuilder.length() - 1) == ',') {
            stringBuilder.replace(stringBuilder.length() - 1, stringBuilder.length(), "");
        }
        return stringBuilder.toString();
    }

    @Override
    protected void onResume() {
        super.onResume();
        toolbar.setNavigationIcon(null);
    }

    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onTimeSet(RadialPickerLayout view, int hourOfDay, int minute) {
        reminder.hour = hourOfDay;
        reminder.minitue = minute;

        String t = String.format("%02d:%02d", hourOfDay, minute);
        tvTime.setText(t);
    }

    @Override
    public void onDateSet(DatePickerDialog datePickerDialog, int year, int month, int day) {
        datePickerDialog.getSelectedDay();
        reminder.year = year;
        reminder.month = month;
        reminder.day = day;
        String t = String.format("%d/%02d/%02d", year , month+1, day);
        tvDate.setText(t);
    }
}
